<template>
  <!-- 批量导入 -->
  <div>
<el-dialog
  :visible.sync="dialogVisible"
  width="35%"
  :before-close="handleClose"
  :close-on-click-modal="false">
  <template slot="title">
    <div class="dicatorName">批量作废</div>
  </template>
  <el-row>
    <el-button  style="float: right; padding: 3px 0" type="text" @click="accomplish('his')">查看历史</el-button>
  </el-row>
  <el-row >
    <el-col :span="24">
      <br>
      <span style="font-weight: bold;">注: 请使用导出模版进行导入需要作废的协议编码：</span>
      <span  style="float: right; padding: 3px 0"><a @click="$message.success('下载成功')"><span style="color: #006AF1">下载导入模板</span></a></span>
    </el-col>
    <el-col :span="24">
      <br>
      <div class="pad-20">
        <el-upload
          class="upload-demo"
          :action="uploadUrl"
          multiple
          :limit="1"
          :headers="header"
          accept=".xlsx, .xls"
          :on-change="handleChange"
          :file-list="fileList">
          <el-button size="small" type="primary">点击上传</el-button>
          <div class="el-upload__tip mt10" style="color:red" slot="tip">提示：仅允许导入一个“xls”或“xlsx”格式文件！</div>
        </el-upload>
      </div>
    </el-col>
  </el-row>
  <span slot="footer" class="dialog-footer">
    <el-button size="small" type="primary" @click="accomplish">开始导入</el-button>
    <el-button size="small" @click="handleClose">取 消</el-button>
  </span>
</el-dialog>

 <!-- 填报结果弹出显示 -->
    <el-dialog title="作废结果" :visible.sync="dialogVisible2" width="50%"  :close-on-click-modal="false">
      <el-row>
        <el-col :span="16">
          <div>
            <el-alert
              :title=title
              :type=type
              show-icon
              :closable="false"
            >
            </el-alert>
          </div>
        </el-col>
        <el-col :span="6" v-if="!isHistory">
          <div>
            <div style="float: right">
              <el-radio-group v-model="radio" size="mini" :span="8" @change="filterData()">
                <el-radio-button label='全部' ></el-radio-button>
                <el-radio-button label='成功' ></el-radio-button>
                <el-radio-button label='失败'></el-radio-button>
              </el-radio-group>
            </div>
          </div>
        </el-col>
      </el-row>


      <div>
        <el-table  height="250" border :data="tableData"  :row-class-name="tableRowClassName" >
          <!-- <el-table-column align="center" type="selection" width="55"></el-table-column> -->
          <el-table-column fixed align="center" prop="index" width="50" label="序号"  :show-overflow-tooltip="true" />
          <el-table-column align="center" prop="code" label="协议编码起始" min-width="180" :show-overflow-tooltip="true"/>
          <el-table-column align="center" prop="result" label="结果"  width="80" :show-overflow-tooltip="true"/>
          <el-table-column align="center" prop="successCount" label="成功数量"  width="80" :show-overflow-tooltip="true"/>
          <el-table-column align="left" prop="reason" label="详细" :show-overflow-tooltip="true"  />
          <el-table-column align="left" prop="createTime" label="创建时间"  width="110" v-if="isHistory" >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column align="left"  label="操作" :show-overflow-tooltip="true" width="60">
            <template v-slot="scope">
              <el-button size="mini" type="text"  @click="openDetail(scope.row)" icon="el-icon-view">查看</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
<!--        <el-button type="primary" size="small"  @click="exportTxt">导出结果为txt文件</el-button>-->
        <el-button size="small" @click="dialogVisible2=false">关 闭</el-button>
        </span>
    </el-dialog>

<!--侧边框-->
    <el-drawer
      :visible.sync="detailOpen"
      direction="rtl"
      size="50%">
      <span slot="title"><font style="color: #1e1e1e;font-size: 18px">协议编码 {{detailTitle}} 作废详细</font></span>
      <!-- 添加搜索框 -->
      <div  style="float: right; padding: 3px 0" >
        <el-input
          placeholder="请输入协议编号进行搜索"
          v-model="searchKeyword"
          @input="handleSearchInput"
        >
          <el-button slot="append" icon="el-icon-search"></el-button>
        </el-input>
      </div>
      <el-table :data="filteredDetailInfo" :row-class-name="tableRowClassName" >
        <el-table-column property="code" label="协议编号" width="150"></el-table-column>
        <el-table-column property="result" label="作废情况" width="200"></el-table-column>
        <el-table-column property="reason" label="原因"></el-table-column>
      </el-table>
    </el-drawer>
  </div>
</template>

<script>
  import { saveAs } from 'file-saver';
  /*import { batchImport } from '@/api/accountManage/insideCheck/custormerInfoLose'*/
  export default{

    props:{
      dialogVisible:{
        default:false
      },

    },
    data() {
      return {
        dialogVisible2: false,
        //url: process.env.VUE_APP_EOS_PROXY+'/customerFunds/datainvestorscategories/com.gf.js.base.fileDownload.flow?downloadFile=C:%2Ftomcat%2Fapache-tomcat-5.5.20%2Fwebapps%2Fdefault%2F%2FcustomerFunds%2Fdatainvestorscategories%2Fcare_temp.xlsx&fileName=投资者职业类别数据规范模板.xlsx'
        url: '/development/exportFillTemplate',
        fillResultData:[ {
          index: 1,
          code: '20044-20050',
          result: '成功',
          reason: '作废成功'
        },
          {
            index: 2,
            code: '2204-2220',
            result: '失败',
            reason: '协议编码冲突，已有相同编码存在，请重新输入。'
          },
          {
            index: 3,
            code: '70019012000000001-7001901200000002',
            result: '成功',
            reason: '存在协议编码不属于该（0101）营业部'
          },
          {
            index: 4,
            code: '7001901200000080-7001901200000090',
            result: '失败',
            reason: '存在协议编码不属于该（0101）营业部'
          }],
        fileList : [],
        header:{token:window.sessionStorage.getItem('token')},
        uploadUrl: process.env.VUE_APP_BASE_API + "/commonUtil/upload",
        baseUrl: process.env.VUE_APP_BASE_API,
        title:'作废成功',
        radio:'全部',
        type:'info',
        tableData:[ {
          index: 1,
          code: '20044-20050',
          result: '成功',
          reason: '作废成功'
        },
          {
            index: 2,
            code: '2204-2220',
            result: '失败',
            reason: '协议编码冲突，已有相同编码存在，请重新输入。'
          },
          {
            index: 3,
            code: '70019012000000001-7001901200000002',
            result: '成功',
            reason: '存在协议编码不属于该（0101）营业部'
          },
          {
            index: 4,
            code: '7001901200000080-7001901200000090',
            result: '失败',
            reason: '存在协议编码不属于该（0101）营业部'
          }],
        detailInfo:[],
        detailOpen: false,
        detailTitle:'',
        searchKeyword: '',
        filteredDetailInfo: this.detailInfo, // 初始值为未经过滤的detailInfo
        isHistory: false

      }
    },
    methods:{
      filterData() {
        //console.log(this.radio + "===========" + this.fillResultData.info);
        if (this.radio === '全部') {
          this.tableData= this.fillResultData
        } else {
          this.tableData = this.fillResultData.filter(item => item.result === this.radio)
        }
      },
      find(){
        console.log(this.radio + "===========");
      },
      filterTag(value, row) {
        return row.result === value;
      },
      //导出为txt
      exportTxt() {
      let tableText = this.fillResultData.info.reduce((text, item) => {
        if(item.result==='成功'){
          return text + `第${item.index}条数据导入成功\r\n`;
        }else{
          return text + `第${item.index}条数据导入失败，原因：${item.reason}\r\n`;
        }

      }, ''); // 将表格数据转换为文本格式
      let blob = new Blob([tableText], { type: 'text/plain;charset=utf-8' }); // 创建txt文件
      saveAs(blob, '批量填报结果.txt'); // 保存txt文件
    },
      /** 文件变化操作 */
    handleChange(file, fileList){
      this.fileList=fileList;
    },

      // 点击完成导入文件
      accomplish(model){

        //let file = this.$refs.uploadfile.fileList;
        if(this.fileList.length>0  || model === 'his'){
        /*  const loading = this.$loading({
            lock: true,
            text: '上传中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          var formData = new FormData();

          formData.append("file",this.fileList[0].raw);
          batchImport(formData).then(res=>{
              if(res.code==200){
                loading.close();
                this.fileList=[]
                this.$emit('close')
                this.$emit('getList')
                this.fillResultData=res.data
                this.tableData=this.fillResultData.info;
                this.title = "一共"+this.fillResultData.total+"条数据,成功填报"+this.fillResultData.successTotal +"条数据,填报失败"+this.fillResultData.failTotal+"条数据"
                this.type = this.fillResultData.failTotal > 0 ? "error" : "success";
                this.dialogVisible2=true
              }
            }).catch(()=>{
              loading.close();
            })*/


          if (model === 'his') {
            this.title = '作废历史'
            this.type = 'info'
            this.isHistory = true

          } else {
            this.$message.success("导入成功")
            this.title = '作废成功，成功作废26条数据'
            this.type = 'warning'
            this.isHistory = false
          }
            this.dialogVisible2=true
            this.tableData=[ {
              index: 1,
              code: '20044-20050',
              result: '成功',
              successCount:17,
              reason: '作废成功',
              createTime:'2024-04-15',
            },
              {
                index: 2,
                code: '2204-2220',
                result: '失败',
                successCount:0,
                reason: '存在协议编码不属于该（0101）营业部',
                createTime:'2024-04-15',
              },
              {
                index: 3,
                code: '70019012000040-70019012000048',
                result: '成功',
                successCount:9,
                reason: '作废成功',
                createTime:'2024-04-15',
              },
              {
                index: 4,
                code: '7001901200000080-7001901200000090',
                result: '失败',
                successCount:0,
                reason: '存在协议编码不属于该（0101）营业部',
                createTime:'2024-04-15',
              }]

          console.log(this.isHistory)

        }else{
          this.$message('请导入文件');
        }
      },

      // 点击关闭与取消
      handleClose(){
        //this.dialogVisible=false;
        this.fileList=[];
        this.$emit('close')
      },

      //表格颜色显示
      tableRowClassName({row, rowIndex}) {
        if (row.result === '失败') {
          return 'warning-row';
        } else if (row.result === '成功') {
          return 'success-row';
        }
        console.log('返回失败' )
        return '';
      },
      openDetail(row){
      //查看详细
        this.detailTitle = row.code;
        this.detailOpen = true;
        this.detailInfo = []
        let codes = row.code.split('-')
        if (row.result === '失败') {
          for (let code = codes[0]; code <=  codes[1]; code++) {
            let item
            console.log(code)
            console.log(code === 2210)
            if (code === 7001901200000085 || code === 2210) {
              console.log(code)
              item ={
                code: String(code), // 将编号转换为字符串
                result: '失败',
                reason: '协议编码: '+String(code)+'，所在营业部编码为（0306）'
              }
            }else{
              item ={
                code: String(code), // 将编号转换为字符串
                result: '成功',
                reason: '可作废'
              }
            }
            this.detailInfo.push(item)
          }
        }else if (row.result === '成功') {
          for (let code = codes[0]; code <=  codes[1]; code++) {
            const item = {
              code: String(code), // 将编号转换为字符串
              result: '成功',
              reason: '作废成功',
            };
            console.log(item)
            this.detailInfo.push(item);
          }
        }
        this.filteredDetailInfo =this.detailInfo

      },
      //详细搜索框
      handleSearchInput(keyword) {
        if (!keyword || keyword === '') {
          this.filteredDetailInfo = this.detailInfo;
          return;
        }
        this.filteredDetailInfo = this.detailInfo.filter(item => item.code.includes(keyword));
      },

    }
  }
</script>

<style lang="scss" scoped>
::v-deep.el-table .warning-row {
  background: #fae0e3;
}

::v-deep.el-table .success-row {
  background: #f0f9eb;
}
</style>


